/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.pro.packaged.O;
import liquibase.pro.packaged.S;
import lombok.AllArgsConstructor;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.modules.repair.dto.ElevatorDetailDTO;
import org.springblade.modules.repair.dto.ElevatorQueryDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.ElevatorUseTypeEnum;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.ElevatorDetailVO;
import org.springblade.modules.repair.vo.ElevatorVO;
import org.springblade.modules.repair.vo.ListElevatorVO;
import org.springblade.modules.repair.vo.NewElevatorPartVO;
import org.springblade.modules.repair.vo.elevator.ElevatorHealthVo;
import org.springblade.modules.repair.vo.elevator.ElevatorPartWorkVo;
import org.springblade.modules.repair.vo.elevator.ElevatorPlanVo;
import org.springblade.modules.repair.vo.plan.ElevatorDriveModeVO;
import org.springblade.modules.repair.vo.rescue.RescuePhoneVo;
import org.springblade.modules.repair.wrapper.ElevatorDriveModeWrapper;
import org.springblade.modules.system.entity.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电梯信息 控制器
 *
 * @author BladeX
 * @since 2021-05-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("repair/maintain/elevator")
@Api(value = "电梯信息管理", tags = "电梯信息管理")
public class ElevatorController extends BladeController {

	private final IElevatorService elevatorService;
	private final ElevatorDetailService elevatorDetailService;
	private final ElevatorDriveModeService elevatorDriveModeService;
	private final ElevatorBrandService elevatorBrandService;


	private static final int PRIVATE_NUM_LENGTH = 20;

	@Autowired
	private ITenantExtService tenantExtService;


	/**
	 * 获取驱动下拉框数据
	 *
	 * @return
	 */
	@GetMapping("/getDriveModeSelect")
	public R<List<ElevatorDriveMode>> getDriveModeSelect() {
		return R.data(elevatorDriveModeService.getDriveModeSelect());
	}

	/**
	 * @return
	 * @Author lsay
	 * @Description {
	 * 获取电梯设备技术参数下拉选择值
	 * }
	 * @Date 16:11 2023/8/12
	 * @Param
	 **/
	@TenantIgnore
	@GetMapping("/driver/mode/field/select")
	public R<List<Dict>> driverModeFieldSelect(String code, String driverModeCode, String driverModeKey) {
		return R.data(elevatorService.driverModeFieldSelect(code, driverModeCode, driverModeKey));
	}


	@GetMapping("getElevatorPhones")
	public R<List<RescuePhoneVo>> getElevatorPhones() {
		String tenantId = AuthUtil.getTenantId();
		TenantExt tenantExt = tenantExtService.getOne(Wrappers.<TenantExt>lambdaQuery().eq(TenantExt::getTenantId, tenantId));
		if (tenantExt != null && tenantExt.getPhoneAllDay() != null && tenantExt.getPhoneAllDay().size() > 0) {
			List<RescuePhoneVo> phoneAllDay = JSON.parseArray(JSON.toJSONString(tenantExt.getPhoneAllDay()), RescuePhoneVo.class);
			return R.data(phoneAllDay);
		}
		return R.data(null);
	}


	/**
	 * 修改 电梯信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入elevator")
	public R update(@Valid @RequestBody Elevator elevator) {
		return R.status(elevatorService.updateById(elevator));
	}


	/**
	 * 修改 电梯信息
	 */
	@PostMapping("/v2/update/")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改", notes = "传入elevator")
	public R updateV2(@Valid @RequestBody Elevator elevator) {
		return R.status(elevatorService.update(elevator));
	}

	@GetMapping("/listElevator")
	public R<List<ListElevatorVO>> listElevator(Long buildingId, String elevatorName) {
		return R.data(elevatorService.listElevator(buildingId, elevatorName));
	}

	@GetMapping("/detail")
	public R<ElevatorDetailVO> detail(Long elevatorId) {
		ElevatorDetailVO elevatorDetailVO = elevatorService.selectElevatorDetail(elevatorId);
		try {
			elevatorDetailVO.setPrivateNumIsFull(checkPrivateNum(elevatorDetailVO.getPrivateNum()));
//			List<String> fulls = new ArrayList<>();
//			fulls.add("isFull");
//			fulls.add("privateNumIsFull");
//			fulls.add("elevatorLatitude");
//			fulls.add("elevatorLongitude");
//			fulls.add("userList");
//			fulls.add("nextPlanDate");
//			fulls.add("previousPlanDate");
//			elevatorDetailVO.setIsFull(CommonUtil.isALLFieldNotNull(elevatorDetailVO, fulls));
			elevatorDetailVO.setIsFull(isFull(elevatorId));
		} catch (Exception e) {
			throw new ServiceException("请求处理异常，请稍后重试！");
		}
		return R.data(elevatorDetailVO);
	}

	/**
	 * 检查电梯设备代码格式
	 *
	 * @param privateNum
	 * @return
	 */
	private Boolean checkPrivateNum(String privateNum) {
		if (ObjectUtil.isEmpty(privateNum)) {
			return Boolean.FALSE;
		}
		int count = elevatorDriveModeService.count(Wrappers.<ElevatorDriveMode>lambdaQuery().eq(ElevatorDriveMode::getCode, privateNum.substring(0, 4)));
		if (count <= 0) {
			return Boolean.FALSE;
		}

//		try {
//			DateUtil.parse(privateNum.substring(10,16),"yyyyMM");
//		}catch (Exception e){
//			return Boolean.FALSE;
//		}
		return Boolean.TRUE;
	}

	@PutMapping("/{id}")
	@ApiOperation("电梯数据更新")
	public R<ElevatorDetailVO> updateElevatorDetail(@PathVariable Long id, @RequestBody ElevatorDetailDTO elevatorDetailDTO) {

		elevatorService.updateElevatorDetail(id, elevatorDetailDTO);
		return R.data(elevatorService.selectElevatorDetail(id));
	}

	@GetMapping("/list/brand")
	public R<?> listElevatorBrand() {
		return R.data(elevatorBrandService.list(Wrappers.<ElevatorBrand>lambdaQuery().orderByDesc(ElevatorBrand::getCreateTime)));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperation(value = "分页")
	public R<IPage<ElevatorVO>> page(Elevator elevator, Query query, BladeUser bladeUser) {
		if (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
			elevator.setTenantId(bladeUser.getTenantId());
		}
		IPage<ElevatorVO> pages = elevatorService.selectElevatorPage(Condition.getPage(query), elevator);
		return R.data(pages);
	}

	/**
	 * 查询人员有实际作业的电梯
	 *
	 * @param queryDTO 查询传参
	 * @param query    分页参数
	 * @return 数据集合
	 */
	@PostMapping("/user/building")
	public R<IPage<ElevatorDetailVO>> getElevatorListByUserDid(@RequestBody ElevatorQueryDTO queryDTO, @RequestBody Query query) {
		return R.data(elevatorService.getElevatorListByUserDid(queryDTO, Condition.getPage(query)));
	}

	/**
	 * @Author lsay
	 * @Description {
	 * 获取电梯设备品种
	 * }
	 * @Date 10:46 2022/10/27
	 **/
	@GetMapping("/drive/mode")
	public R<List<ElevatorDriveModeVO>> getElevatorDriveMode() {
		return R.data(ElevatorDriveModeWrapper.build().listVO(elevatorDriveModeService.list()));
	}

	/**
	 * @Author lsay
	 * @Description {
	 * 获取电梯年审类型
	 * }
	 * @Date 10:46 2022/10/27
	 **/
	@GetMapping("/use/type")
	public R<List<Map<String, Object>>> getElevatorUseType() {
		List<Map<String, Object>> resultMap = Arrays.stream(ElevatorUseTypeEnum.values()).map(e -> {
			Map<String, Object> map = new HashMap<>(2);
			map.put("value", e.getStatus());
			map.put("name", e.getName());
			return map;
		}).collect(Collectors.toList());
		return R.data(resultMap);
	}

	/**
	 * 获取当前项目所有电梯列表
	 * 维保端报障电梯，拉取当前维保公司下，所有的电梯数据
	 */
	@GetMapping("/be/list")
	@ApiOperationSupport(order = 0)
	@ApiOperation(value = "电梯下拉列表")
	public R<IPage<ElevatorVO>> buildingElevatorList(Long buildingId, Query query, String eleName) {
		IPage<ElevatorVO> list = elevatorService.buildingElevatorList(buildingId, Condition.getPage(query), eleName);
		return R.data(list);
	}


	@GetMapping("/getElevatorHealthInfo")
	@ApiOperation(value = "整梯档案信息")
	public R<ElevatorHealthVo> getElevatorHealthInfo(Long elevatorId, Long partId, @RequestParam(required = false) Long floorStandIds) {
		ElevatorHealthVo elevatorHealthVo = elevatorService.getElevatorHealthInfo(elevatorId, partId, floorStandIds);
		return R.data(elevatorHealthVo);
	}


	@GetMapping("/plan/list/byAndWx")
	@ApiOperation(value = "功能故障功能列表")
	public R<List<ElevatorPlanVo>> planListByAndWx(Long elevatorId) {
		List<ElevatorPlanVo> list = elevatorService.planListByAndWx(elevatorId);
		return R.data(list);
	}


	/**
	 * 2023-10-31 新电梯部件详情
	 *
	 * @param elevatorId 当前电梯id
	 * @param partId     当前部件id
	 * @return 电梯基础信息
	 */
	@GetMapping("/newDetail")
	@ApiOperation("新电梯-部件详情")
	@ApiOperationSupport(order = 31)
	public R<NewElevatorPartVO> getNewElevatorPartVO(Long elevatorId, Long partId) {
		NewElevatorPartVO newElevatorPartVO = elevatorService.getNewElevatorPartVO(elevatorId, partId);
		return R.data(newElevatorPartVO);
	}

	/**
	 * 2023-11-01 通用图片详情页
	 *
	 * @param planId 当前工单id
	 * @return 图片详情信息，ElevatorPartWorkVo
	 */
	@GetMapping("/image/detail")
	@ApiOperation("通用图片详情")
	@ApiOperationSupport(order = 32)
	public R<ElevatorPartWorkVo> getElevatorPartWorkDetailImage(Long planId) {
		ElevatorPartWorkVo elevatorPartWorkVo = elevatorService.getElevatorPartWorkDetailImage(planId);
		return R.data(elevatorPartWorkVo);
	}

	/**
	 * 根据电梯id查询电梯完整度
	 */
	@GetMapping("/intact/result")
	@ApiOperation("根据电梯id查询电梯完整度")
	@ApiOperationSupport(order = 31)
	public R<Boolean> intactResult(Long elevatorId) {
		return R.data(isFull(elevatorId));
	}

	private boolean isOk(BigDecimal bigDecimal) {
		if (Func.isNull(bigDecimal) || bigDecimal.compareTo(new BigDecimal("1.00")) < 0) {
			return false;
		}
		return bigDecimal.compareTo(new BigDecimal("1.00")) == 0;
	}

	public boolean isFull(Long elevatorId){
		Elevator currentElevator = elevatorService.getById(elevatorId);
		BigDecimal jgIntact = currentElevator.getJgIntact();
		BigDecimal wbIntact = currentElevator.getWbIntact();
		BigDecimal bxIntact = currentElevator.getBxIntact();
		BigDecimal sbJsIntact = currentElevator.getSbJsIntact();
		BigDecimal sbZcIntact = currentElevator.getSbZcIntact();
		BigDecimal ccIntact = currentElevator.getCcIntact();
		BigDecimal syIntact = currentElevator.getSyIntact();
		BigDecimal azIntact = currentElevator.getAzIntact();
		BigDecimal twyIntact = currentElevator.getTwyIntact();
		return isOk(jgIntact)
			&& isOk(wbIntact)
			&& isOk(bxIntact)
			&& isOk(sbJsIntact)
			&& isOk(sbZcIntact)
			&& isOk(ccIntact)
			&& isOk(syIntact)
			&& isOk(azIntact)
			&& isOk(twyIntact);
	}


}
























